package com.sky.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.Calendar;

@Aspect
@Component
public class AspectStudentJDBC {

    @Value(value = "${spring.datasource.url}")
    private String urlJDBC;//获取数据库连接地址

    @Value(value = "${spring.datasource.username}")
    private String userName;

    @Value(value = "${spring.datasource.password}")
    private String passWord;

    @Pointcut("execution(* com.sky.service.StudentService.*(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void before() throws SQLException {
        Connection connection = DriverManager.getConnection(urlJDBC, userName, passWord);
        Statement statement = connection.createStatement();
        Calendar instance = Calendar.getInstance();
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH);
        String tableName = "student_" + year + "_" + (month + 1);
        ResultSet resultSet = statement.executeQuery("select count(1) as num from information_schema.tables where table_schema = 'sky' and table_name = '" + tableName + "'");
        while (resultSet.next()){
            int num = resultSet.getInt("num");
            if (num == 0){
                Statement statement1 = connection.createStatement();
                statement1.execute("create table " + tableName + " (id int primary key auto_increment,name varchar(20),sex varchar(20),age int,file varchar(20))");
                statement1.close();
            }
        }
        statement.close();
    }
}
